package com.scrx.ymg.dao.seckill;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.scrx.ymg.dao.agent.IAgentInfoDao;
import com.scrx.ymg.dao.base.BaseDaoImpl;
import com.scrx.ymg.entity.AgentInfo;
import com.scrx.ymg.entity.BodyCount;
import com.scrx.ymg.entity.OrderForm;
import com.scrx.ymg.entity.OrderFormDetails;
import com.scrx.ymg.entity.OtherInfo;
import com.scrx.ymg.entity.OtherMoney;
import com.scrx.ymg.entity.SeckillProduct;
import com.scrx.ymg.util.LatLonUtil;

@Repository("seckillDao")
@Transactional
public class SeckillDaoImpl extends BaseDaoImpl implements ISeckillDao {
	@Autowired
	private IAgentInfoDao agentdao;

	public List<SeckillProduct> getSeckillList(int agentID) {
		Query query = getCurrentSession()
				.createQuery("from SeckillProduct where agentId=:id and typeId=0 and status=3 order by startDate ");
		query.setParameter("id", agentID);
		return (List<SeckillProduct>) query.list();
	}

	public SeckillProduct getSeckillOne(int id) {
		Query query = getCurrentSession().createQuery("from SeckillProduct where id=?");
		query.setParameter(0, id);
		return (SeckillProduct) query.uniqueResult();
	}

	public String saveandUpdate(SeckillProduct seckill, OrderForm order, int num) {
		try {
			getCurrentSession().save(order);
			getCurrentSession().update(seckill);
			OrderFormDetails detail = new OrderFormDetails();
			detail.setOrderDetailsId(order.getOrderFormId() + "1");
			detail.setOrderFormId(order.getOrderFormId());
			detail.setOrderId(order.getId());
			detail.setSeckillId(seckill.getId());
			detail.setProductImg(seckill.getProductImg());
			detail.setProductName(seckill.getProductName());
			detail.setTotalPrices(seckill.getSeckillPrice());
			detail.setUnitPrice(seckill.getSeckillPrice());
			detail.setQuantity(num);
			// detail.setProductId(productId);
			getCurrentSession().save(detail);
			return "true";
		} catch (RuntimeException e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}

	public OrderFormDetails getSeckillOrderForm(int userID, int productId) {
		Query query = getCurrentSession().createQuery("from OrderForm where userId=? and typeId=0");
		query.setParameter(0, userID);
		List<OrderForm> list = query.list();
		OrderFormDetails details = null;
		for (OrderForm orderForm : list) {
			Query query1 = getCurrentSession()
					.createQuery("from OrderFormDetails where orderFormId=:id and seckillId=:seckillId");
			query1.setParameter("id", orderForm.getOrderFormId());
			query1.setParameter("seckillId", productId);
			details = (OrderFormDetails) query1.uniqueResult();
		}

		return details;
	}

	public String saveSeckillProduct(SeckillProduct product, MultipartFile productFile, String productFilePath,
			MultipartFile publicityFile, String publicityFilePath, MultipartFile detailFile, String detailFilePath) {
		try {
			this.getCurrentSession().save(product);
			productFile.transferTo(new File(productFilePath));
			publicityFile.transferTo(new File(publicityFilePath));
			detailFile.transferTo(new File(detailFilePath));
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}

	public String updateSeckillOne(SeckillProduct product, MultipartFile productFile, String productFilePath,
			MultipartFile publicityFile, String publicityFilePath, MultipartFile detailFile, String detailFilePath) {
		try {
			this.getCurrentSession().update(product);
			if (detailFile != null && detailFile.getSize() > 0) {
				detailFile.transferTo(new File(detailFilePath));
			}

			if (productFile != null && productFile.getSize() > 0) {
				productFile.transferTo(new File(productFilePath));
			}
			if (publicityFile != null && publicityFile.getSize() > 0) {
				publicityFile.transferTo(new File(publicityFilePath));
			}
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}

	public String deleteSeckillOne(SeckillProduct product) {
		try {
			this.getCurrentSession().delete(product);
			return "true";
		} catch (Exception e) {
			return "false";
		}
	}

	public Map<Object, Object> selectSeckillProductList(SeckillProduct product, int pageNum, int pageCount,
			String startTime, String endTime) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql = new StringBuffer("from SeckillProduct where 1=1 ");
			util.initStartDateTime(startTime, "startDate", hql);
			util.initEndDateTime(endTime, "startDate", hql);
			util.init(product.getStoreName(), "storeName", hql);
			util.init(product.getProductName(), "productName", hql);
			util.initStatus(product.getStatus(), "status", hql);
			util.init(product.getAgentId(), "agentId", hql);
			util.init(product.getTypeId(), "typeId", hql);
			util.init(product.getOtherId(), "otherId", hql);
			util.init(product.getClassifyId(), "classifyId", hql);
			hql.append(" and status not in(-2)  order by startDate desc");
			Query query = getCurrentSession().createQuery(hql.toString());
			List<SeckillProduct> listinfo = query.list();
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<SeckillProduct> list = query.list();
			for (int i = 0; i < list.size(); i++) {
				AgentInfo info = agentdao.getAgentInfoByID(list.get(i).getAgentId());
				list.get(i).setAgentName(info.getAgentName());
			}
			if (product.getAgentId() != null && product.getAgentId() >= 0) {
				map.put("totalAdPrice", getadTotalMoney(product.getAgentId()));
			}

			map.put("list", list);
			map.put("totalpage", (listinfo.size() + pageCount - 1) / pageCount);
			return map;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public double getadTotalMoney(int agentId) {
		LatLonUtil util = new LatLonUtil();
		StringBuffer hql = new StringBuffer(
				"select SUM(adPrice) from SeckillProduct where typeId=0 and status in(3,4)");
		util.init(agentId, "agentId", hql);
		Query query = getCurrentSession().createQuery(hql.toString());
		Iterator iter = query.iterate();
		double num = 0;
		while (iter.hasNext()) {
			Object obj = iter.next();
			if (obj != null) {
				num = Double.parseDouble(obj.toString());
			}
		}
		;
		return num;
	}

	public List<OtherInfo> getOtherInfo(OtherInfo info) {
		try {
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql = new StringBuffer("from OtherInfo where 1=1 ");
			util.init(info.getAgentId(), "agentId", hql);
			util.init(info.getId(), "id", hql);
			util.init(info.getOtherStatus(), "otherStatus", hql);
			Query query = getCurrentSession().createQuery(hql.toString());
			List<OtherInfo> list = query.list();
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public OrderForm getoOrderFormByCode(String code) {
		Query query = getCurrentSession().createQuery("from OrderForm where code=:code");
		query.setParameter("code", code);
		return (OrderForm) query.uniqueResult();
	}

	public OtherInfo getOtherInfoById(Integer id) {
		Query query = getCurrentSession().createQuery("from OtherInfo where id=:id");
		query.setParameter("id", id);
		return (OtherInfo) query.uniqueResult();
	}

	public String updateOtherInfo(OtherInfo oldinfo) {
		try {
			getCurrentSession().update(oldinfo);
			if (oldinfo.getOtherStatus() == 2) {
				Query query = getCurrentSession()
						.createQuery("update SeckillProduct set status=-2 where otherId=:otherId");
				query.setParameter("otherId", oldinfo.getId());
				query.executeUpdate();
			}
			if (oldinfo.getOtherStatus() == 0) {
				Query query = getCurrentSession()
						.createQuery("update SeckillProduct set status=0 where otherId=:otherId");
				query.setParameter("otherId", oldinfo.getId());
				query.executeUpdate();
			}
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}

	}

	public OtherMoney getOtherMoney(int otherId) {
		Query query = getCurrentSession().createQuery("from OtherMoney where otherId=:otherId");
		query.setParameter("otherId", otherId);
		return (OtherMoney) query.uniqueResult();
	}

	public SeckillProduct getSeckillOneByProductName(String productName) {
		Query query = getCurrentSession().createQuery("from SeckillProduct where productName=:productName");
		query.setParameter("productName", productName);
		return (SeckillProduct) query.uniqueResult();
	}

	public BodyCount getBodyCount(BodyCount bodyCount) {
		LatLonUtil util = new LatLonUtil();
		StringBuffer hql = new StringBuffer("from BodyCount where 1=1 ");
		util.init(bodyCount.getSeckillId(), "seckillId", hql);
		Query query = getCurrentSession().createQuery(hql.toString());
		BodyCount listinfo = (BodyCount) query.uniqueResult();
		return listinfo;

	}

	public String updateBodyCount(BodyCount bodyCount) {
		try {
			getCurrentSession().update(bodyCount);
			return "true";
		} catch (Exception e) {
			return "false";
		}
	}

	public String insertBodyCount(BodyCount bodyCount) {
		try {
			getCurrentSession().save(bodyCount);
			return "true";
		} catch (Exception e) {
			return "false";
		}
	}

	public Map<Object, Object> getOtherInfo(OtherInfo info, int pageNum, int pageCount) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql = new StringBuffer("from OtherInfo where 1=1 ");
			util.init(info.getOtherName(), "otherName", hql);
			util.init(info.getOtherPhone(), "otherPhone", hql);
			util.initStatus(info.getOtherStatus(), "otherStatus", hql);
			util.init(info.getAgentRegion(), "agentRegion", hql);
			util.init(info.getAgentId(), "agentId", hql);
			Query query = getCurrentSession().createQuery(hql.toString());
			List<OtherInfo> listinfo = query.list();
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<OtherInfo> list = query.list();
			AgentInfo ageninfo = null;
			OtherMoney money = null;
			double totalMoney = 0.0;
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					ageninfo = agentdao.getAgentInfoByID(list.get(i).getAgentId());
					money = getOtherMoney(list.get(i).getId());
					list.get(i).setAgentName(ageninfo.getAgentName());
					list.get(i).setTotalMoney(money.getTotalMoney());
					totalMoney += money.getTotalMoney();
				}
			}
			map.put("list", list);
			map.put("totalpage", (listinfo.size() + pageCount - 1) / pageCount);
			map.put("totalMoney", totalMoney);
			return map;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public String updateOtherInfo(OtherInfo other, OtherMoney newmoney) {
		try {
			this.getCurrentSession().update(other);
			this.getCurrentSession().save(newmoney);
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}

	public String deleteOtherInfo(OtherInfo oldother) {
		try {
			this.getCurrentSession().delete(oldother);
			return "true";
		} catch (Exception e) {
			return "false";
		}
	}

	public SeckillProduct getSeckillByDateAndAgentId(String startDate, Integer agentId) {
		Query query = getCurrentSession()
				.createQuery("from SeckillProduct where startDate=:startDate and agentId=:agentId");
		query.setParameter("startDate", startDate);
		query.setParameter("agentId", agentId);
		return (SeckillProduct) query.uniqueResult();
	}

	public SeckillProduct getSeckillOneByOrderNum(String orderNum) {
		Query query = getCurrentSession().createQuery("from SeckillProduct where orderNum=:orderNum");
		query.setParameter("orderNum", orderNum);
		return (SeckillProduct) query.uniqueResult();
	}

	public String saveSeckill(SeckillProduct seckill) {
		try {
			this.getCurrentSession().save(seckill);
			return "true";
		} catch (Exception e) {
			return "false";
		}
	}

	public String updateSeckillProduct(SeckillProduct seckill) {
		try {
			this.getCurrentSession().update(seckill);
			return "true";
		} catch (Exception e) {
			return "false";
		}
	}

	public String updateSeckillProductAD(String thisTime) {
		Query query = getCurrentSession().createQuery(
				"update SeckillProduct set status=4 where status=3 and typeId=0 and" + " startDate<=:thistime");
		query.setParameter("thistime", thisTime);
		int num = query.executeUpdate();
		return "true";
	}

}
